<?php

namespace App\Models\Receivemoney;

use App\Models\Settle\SettleType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class Receipt extends Model
{
    protected $table = 'sale_receipt';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     * 列表
     */
    public static function getList(Request $request, $memberinfo, $isgetall)
    {
        $query = self::orderBy('create_at', 'desc');
        $cpid = $memberinfo['cpid'] ?? 0;
        $utype = $memberinfo['utype'] ?? 0;
        $manger_id = $memberinfo['id'] ?? 0;
        // $sys_dpm_id = $memberinfo['sys_dpm_id'] ?? 0;

        $custom_name = $request->custom_name;
        if ($custom_name != '') {
            $query->where('custom_name', 'like', '%' . $custom_name . '%');
        }
        $settlement_company = $request->settlement_company??'';
        if ($settlement_company != '') {
            $query->where('settlement_company', 'like', '%'. $settlement_company . '%');
        }

        $settlement_category = $request->settlement_category??'';
        if ($settlement_category != '') {
            $query->where('settlement_category', $settlement_category);
        }
        $settlement_category_id = $request->settlement_category_id??0;
        if ($settlement_category_id > 0) {
            $query->where('settlement_category_id', $settlement_category_id);
        }
        /**
         *  业务员只能看到自己的收款单数据 2025.04.03
         *
        */
        if($utype == '7'){
            $query->where('manger_id', $manger_id);
        }

        if ($cpid > 0) {
            $query->where('cpid', $cpid);
        }

        //$today = date("Y-m-d");
        $start_time = isTimestamp($request->start_time)?$request->start_time:strtotime($request->start_time);
        if ($start_time != '') {
            $query->where('date', '>=', $start_time);
        }
        $end_time = isTimestamp($request->end_time)?$request->end_time:strtotime($request->end_time);
        if ($end_time != '') {
            $query->where('date', '<=', $end_time);
        }

        // if ($sys_dpm_id > 0) {
        //     $query->where('sys_dpm_id', $sys_dpm_id);
        // }

        $code = $request->code;
        if ($code != '') {
            $query->where('code', $code);
        }

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    /**
     * 详情
     */
    public static function getone($id)
    {
        return self::where('id', $id)->get();
    }

    public function settlement_category_info(){
        return $this->hasOne(SettleType::class, 'id', 'settlement_category');
    }
}
